package com.falcon.web.controller;

import com.falcon.core.domain.BaseResponse;
import com.falcon.web.domain.LoginRequest;
import com.falcon.web.domain.LoginResponse;
import com.swan.security.domain.SecurityUserInfo;
import com.swan.security.token.JwtTokenManager;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private JwtTokenManager jwtTokenManager;

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public BaseResponse<LoginResponse> login(@RequestBody LoginRequest request){
        // 登录授权, 校验用户密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        // 将登录用户信息交给SpringSecurity管理
        SecurityContextHolder.getContext().setAuthentication(authentication);

        SecurityUserInfo securityUserInfo = (SecurityUserInfo) authentication.getPrincipal();

        // 利用用户授权信息生成JWT令牌
        String token = jwtTokenManager.generateToken(securityUserInfo);

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setUsername(request.getUsername());
        loginResponse.setAccessToken(token);
        return BaseResponse.success(loginResponse);
    }

    @PostMapping("/refresh")
    public BaseResponse<String > refresh(HttpServletRequest request){

        String token = this.jwtTokenManager.resolveToken(request);

        // 校验token 有效性
        boolean isValid = this.jwtTokenManager.validateToken(token);
        if (!isValid) {
            throw new BadCredentialsException("Token 已过期");
        }

        String newToken = this.jwtTokenManager.refreshToken(token);
        return BaseResponse.success(newToken);
    }

}

